const { Sequelize, DataTypes } = require("sequelize");
const { v4: uuidv4 } = require("uuid");

const sequelize = new Sequelize(
  process.env.DB_DATABASE,
  process.env.DB_USER,
  process.env.DB_PASSWORD,
  {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT || 3306,
    dialect: "mysql",
    logging: false,
    define: {
      defaultPrimaryKey: true,
      defaultIdType: DataTypes.UUID,
      //   hooks: {
      //     beforeCreate: (user, options) => {
      //       console.log("beforeCreate", user, options);
      //     },
      //   },
    },
  }
);

sequelize.UUIDV4 = uuidv4;

sequelize.beforeDefine((attributes, options) => {
  // 添加默认 id 字段为 UUID 主键
  const idAttr = {
    type: DataTypes.UUID,
    primaryKey: true,
    defaultValue: sequelize.UUIDV4
  };
  attributes.id = idAttr;
  return attributes;
});

// (async function () {
//   try {
//       await sequelize.authenticate();
//       console.log('Connection has been established successfully.');
//   } catch (error) {
//       console.error('Unable to connect to the database:', error);
//   }
// }())

module.exports = sequelize;
